<?php
/**
 * vgoshop
 * ============================================================================
 * 网站地址: http://www.vgo.me
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: myhonour
 * DateTime: 2017/10/9 下午9:40
 */

namespace app\admin\controller;


use app\admin\model\Themes;
use think\Request;

class Template extends Common
{
    public function lists($path = NULL){
        // 获取 themes 主题
        $themesPath =   ROOT_PATH.'themes'.DS;
        $themes =   Themes::themeList($themesPath);
        $this->assign('themes',$themes);
        $themesHtml =   is_null($path)?(isset($themes[0])?$themes[0]['path']:'default'):$path;
//        $themesFiles = $themesPath.$themesHtml.DS;
        $files =  Themes::fileList($themesHtml.DS);
        $this->assign('files',$files);
        return $this->fetch();
    }

    public function editFile(Request $request,$path){
        if (!is_file($path) OR (substr(strrchr($path,'.'),1) != 'html')){
            $this->error('无法进行编辑！');
        }
        $request->isPost() AND $this->editFileSave($path);
        $this->assign('content',file_get_contents($path));
        $this->assign('name',basename($path));
        return $this->fetch();
    }

    private function editFileSave($path){
        $content = input('post.content','','htmlspecialchars_decode');
        if (file_put_contents($path,$content)){
            $this->success('更新成功！');
        }
        $this->error('更新失败！');
    }

//    private function fileList($path){
//        $fileList =    [];
//        if(!$pathRes    =   opendir($path)){
//            return $fileList;
//        };
//        while (($file = readdir($pathRes)) !== FALSE){
//            if ($file != '.' && $file != '..' && is_dir($path.$file)){
//                $fileList = array_merge($fileList,$this->fileList($path.$file.DS));
//            }
//            if ($file != '.' && $file != '..' && is_file($path.$file) && (substr(strrchr($file,'.'),1) == 'html')){
//                $fileList[]  =   ['name' =>  $file,'path' => $path.$file,'sortPath' =>  str_replace(ROOT_PATH,'',$path.$file)];
//            }
//        }
//        return $fileList;
//    }
//
//    /** 获取文件夹
//     * @param $path
//     * @return array
//     */
//    private function themeList($path){
//        $dir    =   [];
//        if(!$pathRes    =   opendir($path)){
//            return $dir;
//        };
//        while (($file = readdir($pathRes)) !== FALSE){
//            if ($file != '.' && $file != '..' && is_dir($path.$file)){
//                $dir[]  =   ['name' =>  $file,'path' => $path.$file];
//            }
//        }
//        return $dir;
//    }
}